package com.example.demo.nio.socket;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;

/**
 * Description: <br/>
 *
 * @author LLL<br                                                                                                                               />;
 * @taskId <br/>
 * @Date 2019/5/30 17:06
 * @Version 1.0
 */
@Slf4j
public class EchoClient {

    private Socket socket1;

    private Socket socket2;

    public EchoClient() throws IOException {
        socket1 = new Socket("127.0.0.1", 9999);
        socket2 = new Socket("127.0.0.1", 9999);

        log.info("与服务端建立连接成功....");
    }

    private PrintWriter getPrintWriter(Socket socket) throws IOException {
        OutputStream socketOutputStream = socket.getOutputStream();
        return new PrintWriter(socketOutputStream, true);
    }

    private BufferedReader getBufferedReader(Socket socket) throws IOException {
        InputStream socketInputStream = socket.getInputStream();
        return new BufferedReader(new InputStreamReader(socketInputStream));
    }

    public void talk() {
        try {
            BufferedReader reader = getBufferedReader(socket1);
            PrintWriter writer = getPrintWriter(socket1);
            BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in));
            String msg = null;
            while ((msg = localReader.readLine()) != null) {
                writer.println(msg);
                System.out.println(reader.readLine());
                if (msg.equals("bye")) {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket1 != null) {
                try {
                    socket1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        new EchoClient().talk();
    }
}
